import requests
from config import *

def get_file_name_from_language_best(language:str)->str:
    """
    根据语言代码获取文件名；
    调用：  print(get_file_name_from_language_best('zh'))
    """
    lang_best=language_voice_map_best[language]
    opentts_dict=opentts_voice_map[lang_best]
    wav_name=f"{opentts_dict['language']}_{opentts_dict['name']}_{opentts_dict['tts_name']}_[{opentts_dict['gender']}].wav"
    return f"{wav_name}"

def get_file_name_from_language_name_best(language_chinese_name:str)->str:
    """
    根据语言名称获取文件名；
    调用：    print(get_file_name_from_language_name_best('中文普通话'))
    """
    language = whisper_name_language_map.get(language_chinese_name, "en")
    lang_best=language_voice_map_best[language]
    opentts_dict=opentts_voice_map[lang_best]
    wav_name=f"{opentts_dict['language']}_{opentts_dict['name']}_{opentts_dict['tts_name']}_[{opentts_dict['gender']}].wav"
    return f"{wav_name}"

def add_dict_to_response(response, extra_dict):
    """
    将额外的字典数据附加到 Response 对象上，并返回修改后的 Response
    
    Args:
        response (requests.Response): 原始 Response 对象
        extra_dict (dict): 要添加的额外数据
    
    Returns:
        requests.Response: 修改后的 Response，新增 `.custom_data` 属性
    """
    # 动态添加属性（不影响原始 Response 的功能）
    response.custom_data = extra_dict
    return response

def get_tts(language, text,save_audio=True):
    """
    根据指定的语言和文本获取TTS音频
    
    Args:
        language: 语言代码，如'zh'、'en'等
        text: 要转换为语音的文本
        
    Returns:
        音频数据(wav格式)-位于response.content；
    """
    voice = language_voice_map_best.get(language, "espeak:en")
    params_tts = {
        "voice": voice,
        "text": text
    }
    
    response = requests.get(tts_base_url, params=params_tts)

    if response.status_code == 200:
        if save_audio:
            file_name=get_file_name_from_language_best(language)
            with open(file_name, 'wb') as f:
                f.write(response.content)
            print(f"音频已保存到 {file_name}")
        return response.content
    else:
        print(f"错误: {response.status_code}")
        return None

def get_tts_from_whisper_chinese_name(language_chinese_name, text,save_audio=True):
    """
    根据whisper指定的中文语言名称，使用opentts进行tts；
    优点：自动选择最佳voice（试听后，手动确定的优先级）；
    Args:
        language: 语言代码，如'zh'、'en'等
        text: 要转换为语音的文本
        
    Returns:
        音频数据(wav格式)
    """
    language = whisper_name_language_map.get(language_chinese_name, "en")
    voice = language_voice_map_best.get(language, "espeak:en")
    params_tts = {
        "voice": voice,
        "text": text
    }
    
    response = requests.get(tts_base_url, params=params_tts)

    if response.status_code == 200:
        if save_audio:
            file_name=get_file_name_from_language_name_best(language_chinese_name)
            with open(file_name, 'wb') as f:
                f.write(response.content)
            print(f"音频已保存到 {file_name}")
        return response.content
    else:
        print(f"错误: {response.status_code}")
        return None

    
# 示例用法
if __name__ == "__main__":
    # 使用新函数示例
    get_tts('zh', '这是一个测试')
    # get_tts_from_whisper_chinese_name('中文普通话', '这是一个测试')
    # get_tts_from_whisper_chinese_name('俄语', 'Это тест.')

